//
//  HELoginViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/9/29.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HELoginViewController.h"
#import "HELoginRequest.h"
#import "HEOtherBindPhoneViewController.h"
#import <AuthenticationServices/AuthenticationServices.h>
#import "HEUpdateAlert.h"

@interface HELoginViewController ()<ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>

@property (weak, nonatomic) IBOutlet UIView *warpView;
@property (weak, nonatomic) IBOutlet UIImageView *logoView;
@property (weak, nonatomic) IBOutlet QMUITextField *usernameTF;

@property (weak, nonatomic) IBOutlet UILabel *descLb;

@property(nonatomic, strong) QMUIFillButton *codeBtn;
@property(nonatomic, strong) QMUITextField *codeTF;
@property(nonatomic, strong) QMUIFillButton *loginBtn;
@property (nonatomic, assign) BOOL frist;

@end

@implementation HELoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // 检测版本更新
//    [HEUpdateAlert checkNewEditionWithAppID:APPID ctrl:self];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(otherAuthNotif:) name:KNotificationOtherAuthSuccess object:nil];
    
    [self initUI];
}

- (void)initUI {

    // logo
    _logoView.layer.cornerRadius = 35;
    _logoView.layer.masksToBounds = YES;
    
    // 账户
    self.usernameTF.backgroundColor = [UIColor qmui_colorWithHexString:@"F1F3F8"];
    self.usernameTF.maximumTextLength = 11;
    self.usernameTF.placeholder = @"请输入手机号";
    self.usernameTF.font = UIFontMake(15);
    self.usernameTF.layer.cornerRadius = 4;
    self.usernameTF.textInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    self.usernameTF.clearButtonMode = UITextFieldViewModeAlways;
    self.usernameTF.keyboardType = UIKeyboardTypeNumberPad;

    // 验证码
    _codeTF = [[QMUITextField alloc] init];
    self.codeTF.backgroundColor = [UIColor qmui_colorWithHexString:@"F1F3F8"];
    self.codeTF.maximumTextLength = 6;
    self.codeTF.placeholder = @"请输入验证码";
    self.codeTF.font = UIFontMake(15);
    self.codeTF.layer.cornerRadius = 4;
    self.codeTF.keyboardType = UIKeyboardTypeNumberPad;
    self.codeTF.textInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    self.codeTF.clearButtonMode = UITextFieldViewModeAlways;
    [_warpView addSubview:self.codeTF];
    
    // 发送验证码按钮
    _codeBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorBlue];
    self.codeBtn.titleLabel.font = UIFontMake(14);
    [self.codeBtn setBackgroundColor:CNavBgColor];
    [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_warpView addSubview:self.codeBtn];
    [_codeBtn addTarget:self action:@selector(sendSMS) forControlEvents:UIControlEventTouchUpInside];
    
    // 登录按钮
    _loginBtn = [[QMUIFillButton alloc] initWithFillType:QMUIFillButtonColorBlue];
    self.loginBtn.titleLabel.font = UIFontMake(15);
    [self.loginBtn setBackgroundColor:CNavBgColor];
    [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [_warpView addSubview:self.loginBtn];
    [self.loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
  
    
    // 协议
    YYLabel *notesPLb = [[YYLabel alloc] init];
    notesPLb.textVerticalAlignment = YYTextVerticalAlignmentTop;
    notesPLb.textAlignment = NSTextAlignmentLeft;
    [_warpView addSubview:notesPLb];

    NSDictionary *attributes = @{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:15], NSForegroundColorAttributeName: [UIColor blackColor]};

    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"  登录代表同意《注册会员条款》和《隐私政策》" attributes:attributes];
    //设置高亮色和点击事件
    [text yy_setTextHighlightRange:[[text string] rangeOfString:@"《注册会员条款》"] color:CNavBgColor backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [self toSeeProtcal:@"https://www.honglutec.com/agreement/member.html"];
    }];

    //设置高亮色和点击事件
    [text yy_setTextHighlightRange:[[text string] rangeOfString:@"《隐私政策》"] color:CNavBgColor backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [self toSeeProtcal:@"https://www.honglutec.com/agreement/yszc.html"];
    }];
    notesPLb.numberOfLines = 0;
    notesPLb.preferredMaxLayoutWidth = KScreenWidth - 120;
    notesPLb.attributedText = text;
    
    
    
    [_warpView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).mas_offset(90);
        make.centerX.equalTo(self.view);
        make.left.equalTo(self.view).mas_offset(20);
        make.right.equalTo(self.view).mas_offset(-20);
    }];
    
    [_logoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_warpView).mas_offset(23);
        make.centerX.equalTo(_warpView);
        make.width.height.mas_offset(70);
    }];
    
    [_usernameTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_logoView.mas_bottom).mas_offset(30);
        make.centerX.equalTo(_warpView);
        make.left.equalTo(_warpView).mas_offset(30);
        make.right.equalTo(_warpView).mas_offset(-30);
        make.height.mas_offset(40);
    }];
    
    [_codeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_codeTF);
        make.height.mas_offset(34);
        make.width.mas_offset(100);
        make.right.equalTo(_warpView.mas_right).mas_offset(-30);
    }];
    
    [_codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_usernameTF.mas_bottom).mas_offset(20);
        make.left.equalTo(_warpView).mas_offset(30);
        make.right.equalTo(_warpView).mas_offset(-150);
        make.height.mas_offset(40);
    }];
    
    [_loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_codeTF.mas_bottom).mas_offset(30);
        make.left.equalTo(_warpView).mas_offset(30);
        make.right.equalTo(_warpView.mas_right).mas_offset(-30);
        make.height.mas_offset(40);
    }];
    
    [notesPLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_loginBtn.mas_bottom).mas_offset(20);
        make.left.equalTo(_warpView.mas_left).mas_offset(20);
        make.right.equalTo(_warpView.mas_right).mas_offset(-20);
        make.height.mas_greaterThanOrEqualTo(10);
        make.bottom.equalTo(_warpView.mas_bottom).mas_offset(-10);
    }];
    
    [notesPLb setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
    
    [_descLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_warpView.mas_bottom).mas_offset(20);
        make.centerX.equalTo(self.view);
    }];
    
    // 因为老人端与家庭端同一个账户问题 暂不能使用微信登录
    if (@available(iOS 13.0, *)) {
        
        UIView *spLine = [UIView new];
        spLine.backgroundColor = CSplitLineColor;
        [self.view addSubview:spLine];
        
        UILabel *loginMethodLb = [UILabel new];
        loginMethodLb.text = @"其它登录方式";
        loginMethodLb.textColor = CNavDargGrayColor;
        loginMethodLb.backgroundColor = KWhiteColor;
        loginMethodLb.textAlignment = NSTextAlignmentCenter;
        loginMethodLb.font = UIFontMake(15);
        [self.view addSubview:loginMethodLb];
        
        ASAuthorizationAppleIDButton *appleButon = [[ASAuthorizationAppleIDButton alloc]initWithAuthorizationButtonType:ASAuthorizationAppleIDButtonTypeSignIn authorizationButtonStyle:ASAuthorizationAppleIDButtonStyleBlack];
        appleButon.cornerRadius = 45 / 2.0;
        [appleButon addTarget:self action:@selector(appleSignAction) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview: appleButon];

        [appleButon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(loginMethodLb.mas_bottom).mas_offset(15);
            make.centerX.equalTo(self.view);
            make.width.mas_offset(45);
            make.height.mas_offset(45);
        }];
        
        
        [loginMethodLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_descLb.mas_bottom).offset(15);
            make.centerX.equalTo(self.view);
            make.width.offset([loginMethodLb.text widthForFont:loginMethodLb.font] + 20);
        }];
        [spLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(loginMethodLb);
            make.width.offset([loginMethodLb.text widthForFont:loginMethodLb.font] + 20 + 100);
            make.centerX.equalTo(loginMethodLb);
            make.height.offset(1);
        }];
    }
    
    
    NSString *phone = (NSString *)[kUserDefaults objectForKey:KUserName];
    _usernameTF.text = phone;
}

#pragma mark -
-(void)appleSignAction{
    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDProvider *provider = [[ASAuthorizationAppleIDProvider alloc] init];
        ASAuthorizationAppleIDRequest *request = [provider createRequest];
        request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
        
        ASAuthorizationController *vc = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
        vc.delegate = self;
        vc.presentationContextProvider = self;
        [vc performRequests];
        
    }
}

- (void)toWxLoginClick {
    if([WXApi isWXAppInstalled]){//判断用户是否已安装微信App
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.state = @"wx_oauth_authorization_state";//用于保持请求和回调的状态，授权请求或原样带回
        req.scope = @"snsapi_userinfo";//授权作用域：获取用户个人信息
        //唤起微信
        [WXApi sendReq:req completion:^(BOOL success) {
            
        }];
    }else{
        [Dialog toastBottom:@"未安装微信应用或版本过低"];
    }
}

- (void)toSeeProtcal:(NSString *)protcalName {
//    NSString * fileUrl = [[NSBundle mainBundle]pathForResource:protcalName ofType:@"html"];
//    NSURL * file = [NSURL fileURLWithPath:fileUrl];
 
    NSURL * file = [NSURL URLWithString:protcalName];

    RootWebViewController *webView = [[RootWebViewController alloc] initWithUrl:file.absoluteString];
    webView.isShowCloseBtn = YES;
    webView.showPageTitle = YES;
    RootNavigationController *nav = [[RootNavigationController alloc] initWithRootViewController:webView];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)setupShadow {
    [_warpView addCornersAndShadow];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    if (!_frist) {
        [self setupShadow];
        _frist = true;
    }
}


- (void)sendSMS {
    
    NSString *phone = _usernameTF.text;
    
    // 判断手机号格式是否正确
    if (![WOValidate valiMobile:phone]) {
         [Dialog toast:@"请输入正确的手机号码" delay:2];
        return;
    }
    
    // 记录手机号
    [kUserDefaults setObject:phone forKey:KUserName];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:phone forKey:@"phone"];
    [params setObject:@"sms_login" forKey:@"smsType"];
    [params setObject:[NSNumber numberWithInt:1] forKey:@"source"];

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KSendSMSUrl parameters:params token:nil success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];

        if (response.success) {
            [Dialog toast:@"短信发送成功" delay:2];
            [self openCountdown];
        }
        DLog(@"%@",responseObject);
    } failure:^(NSError * _Nonnull error) {

    }];
}

#pragma makr - Login click
- (void)loginBtnClick {
    HELoginRequest *user = [HELoginRequest new];
    user.username = self.usernameTF.text;
    user.password = [DYTools md5:[NSString stringWithFormat:@"%@%@",self.usernameTF.text, kHash]];
    user.smsCode = self.codeTF.text;
    user.registrationId = [JPUSHService registrationID];
    user.method = @"smsLogin";
    user.source = 1;
    user.platform = @"ios";
    user.deviceModel = [WOAppModel ShareAppModel].deviceVersion;
    user.deviceId = [WOAppModel ShareAppModel].idfv;
    user.version = [WOAppModel ShareAppModel].appVersion;
    user.versionCode = [WOAppModel ShareAppModel].appBuild;
    user.systemVersion = [[UIDevice currentDevice] systemVersion];
    
    BOOL flag = [self check:user];
    
    if (!flag) {
        return;
    }
    
    // 记录手机号
    [kUserDefaults setObject:user.username forKey:KUserName];
    
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KLoginUrl parameters:user token:nil success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        
        if (!response.success) {
            return;
        }
         
        UserInfo *data = [UserInfo mj_objectWithKeyValues:response.data];
        
        // 存储用户数据
        [[UserManager sharedUserManager] saveUserInfo:data];
        
        // 存储token
        [[UserManager sharedUserManager] saveToken:response.jwtToken forKey:data.username];
        
        // 连接socket
        [[HESocketManager sharedManager] connect]; 
     
        MainTabBarController *tabBarViewController = [[MainTabBarController alloc] init];
        kAppDelegate.mainTabBar = tabBarViewController;
        self.view.window.rootViewController = tabBarViewController;
        [self.view.window makeKeyAndVisible];
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - 苹果授权登录
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization {
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]])       {
        ASAuthorizationAppleIDCredential *credential = authorization.credential;

        NSLog(@"credential = %@",credential);

        NSString *state = credential.state;

        // 苹果用户唯一标识符，该值在同一个开发者账号下的所有 App 下是一样的，开发者可以用该唯一标识符与自己后台系统的账号体系绑定起来。
        NSString *userID = credential.user;
        NSPersonNameComponents *fullName = credential.fullName;
        NSString *email = credential.email;
        NSString *authorizationCode = [[NSString alloc] initWithData:credential.authorizationCode encoding:NSUTF8StringEncoding]; // 验证 token
        NSString *identityToken = [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding]; // 用户 token
        ASUserDetectionStatus realUserStatus = credential.realUserStatus;
        NSArray *authorizedScopes = credential.authorizedScopes;

        HELoginRequest *loginReq = [HELoginRequest new];
        loginReq.authCode = identityToken;
        loginReq.method = @"appleLogin";
        loginReq.type = 1;
        loginReq.platform = @"iOS";
        loginReq.source = 1;
        loginReq.identityType = @"apple";
        loginReq.registrationId = [JPUSHService registrationID];

        [self authLoginReq: loginReq];
           
           NSLog(@"state: %@\nuserID: %@\nfullName: %@\nemail: %@\nauthorizationCode: %@\nidentityToken: %@\nrealUserStatus: %@\nauthorizedScopes: %@",
                 state,
                 userID,
                 fullName,
                 email,
                 authorizationCode,
                 identityToken,
                 @(realUserStatus),
                 authorizedScopes);
    }
}

- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error {
       NSString *errorMsg = nil;
       switch (error.code) {
           case ASAuthorizationErrorCanceled:
               errorMsg = @"用户取消了授权请求";
               break;
           case ASAuthorizationErrorFailed:
               errorMsg = @"授权请求失败";
               break;
           case ASAuthorizationErrorInvalidResponse:
               errorMsg = @"授权请求响应无效";
               break;
           case ASAuthorizationErrorNotHandled:
               errorMsg = @"未能处理授权请求";
               break;
           case ASAuthorizationErrorUnknown:
               errorMsg = @"授权请求失败未知原因";
               break;
       }
}

- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller {
    return self.view.window;
}
 
#pragma mark - 微信授权登录
- (void)otherAuthNotif:(NSNotification *)notif {
    NSString *code = (NSString *)notif.object;
    
    HELoginRequest *loginReq = [HELoginRequest new];
    loginReq.authCode = code;
    loginReq.method = @"weChatLogin";
    loginReq.type = 1;
    loginReq.platform = @"iOS";
    loginReq.source = 1;
    loginReq.identityType = @"weChat";
    loginReq.registrationId = [JPUSHService registrationID];

    [self authLoginReq: loginReq];
}

- (void)authLoginReq:(HELoginRequest *)loginReq {
   
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KLoginUrl parameters:loginReq token:nil success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];

        if (response.code == 712) { // 该微信号暂未绑定用户
            HEOtherBindPhoneViewController *vc = [HEOtherBindPhoneViewController new];
            vc.openId = response.data[@"openId"];
            vc.unionId = response.data[@"unionId"];
            vc.intoType = HEOtherBindPhoneTypeAuth;
            vc.method = loginReq.method;
            vc.identityType = loginReq.identityType;
            HEBaseNavigationController *nav = [[HEBaseNavigationController alloc] initWithRootViewController:vc];
            [self presentViewController:nav animated:YES completion:nil];
        }else if (response.code == 203) { // 已绑定 登录
            UserInfo *data = [UserInfo mj_objectWithKeyValues:response.data];
            
            // 存储用户数据
            [[UserManager sharedUserManager] saveUserInfo:data];
            
            // 存储token
            [[UserManager sharedUserManager] saveToken:response.jwtToken forKey:data.username];
            
            // 连接socket
            [[HESocketManager sharedManager] connect];
         
            MainTabBarController *tabBarViewController = [[MainTabBarController alloc] init];
            kAppDelegate.mainTabBar = tabBarViewController;
            self.view.window.rootViewController = tabBarViewController;
            [self.view.window makeKeyAndVisible];
        }
    } failure:^(NSError * _Nonnull error) {

    }];
}

- (BOOL)check:(HELoginRequest *)user {
    
    // 判断手机号格式是否正确
    if (![WOValidate valiMobile:user.username]) {
        [Dialog toast:@"请输入正确的手机号码" delay:2];
        return NO;
    }
    
    if ([DYTools isBlankString:_codeTF.text]) {
        [Dialog toastBottom:@"请输入验证码"];
        return NO;
    }
    
    return YES;
}

// 开启倒计时效果
- (void)openCountdown{

    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{

                //设置按钮的样式
                [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                self.codeBtn.userInteractionEnabled = YES;
            });

        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{

                //设置按钮显示读秒效果
                [self.codeBtn setTitle:[NSString stringWithFormat:@"%ldS", seconds] forState:UIControlStateNormal];
                self.codeBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
